package org.example.im.service.impl;

import org.example.im.dto.MessageDTO;
import org.example.im.entity.Message;
import org.example.im.entity.User;
import org.example.im.repository.MessageRepository;
import org.example.im.service.MessageService;
import org.example.im.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {
    
    @Autowired
    private MessageRepository messageRepository;
    
    @Autowired
    private UserService userService;
    
    @Override
    public Message saveMessage(MessageDTO messageDTO) {
        Message message = new Message();
        message.setSenderId(messageDTO.getSenderId());
        message.setReceiverId(messageDTO.getReceiverId());
        message.setContent(messageDTO.getContent());
        message.setMessageType(messageDTO.getMessageType());
        message.setChatType(messageDTO.getChatType());
        message.setSendTime(new Date());
        message.setFileUrl(messageDTO.getFileUrl());
        
        return messageRepository.save(message);
    }
    
    @Override
    public List<MessageDTO> getPrivateMessages(Long userId1, Long userId2) {
        List<Message> messages = messageRepository.findPrivateMessages(userId1, userId2);
        return messages.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public List<MessageDTO> getGroupMessages() {
        List<Message> messages = messageRepository.findGroupMessages();
        return messages.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    private MessageDTO convertToDTO(Message message) {
        MessageDTO dto = new MessageDTO();
        dto.setId(message.getId());
        dto.setSenderId(message.getSenderId());
        dto.setMessageType(message.getMessageType());
        dto.setChatType(message.getChatType());
        dto.setContent(message.getContent());
        dto.setSendTime(message.getSendTime());
        dto.setFileUrl(message.getFileUrl());
        
        try {
            User sender = userService.getUserById(message.getSenderId());
            dto.setSenderName(sender.getUsername());
            
            if (message.getReceiverId() != null) {
                User receiver = userService.getUserById(message.getReceiverId());
                dto.setReceiverId(message.getReceiverId());
                dto.setReceiverName(receiver.getUsername());
            }
        } catch (Exception e) {
            // 忽略不存在的用户
        }
        
        return dto;
    }
} 